package cn.zhage.aimin.ai.controller;

import cn.zhage.aimin.ai.service.FileUploadService;
import cn.zhage.aimin.base.response.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/*
 *
 * @author 渣哥
 */
@RestController
@RequestMapping("/rag")
@RequiredArgsConstructor
public class RagController {

    private final FileUploadService fileUploadService;

    private final VectorStore vectorStore;

    @PostMapping("/upload")
    public Result<?> upload(@RequestParam("file") MultipartFile file) {
        fileUploadService.upload(file);
        return Result.success();
    }



    @GetMapping("/search")
    public Result<?> search(String question) {

        // 根据问题调用模型生成关键词

        FilterExpressionBuilder b = new FilterExpressionBuilder();

        SearchRequest searchRequest = SearchRequest.builder()
                .query(question)
                .filterExpression(b.in("excerpt_keywords",  "Keywords: 眼睛, 滴眼药水").build())
                .similarityThreshold(0.4)  //按照阈值做相似查询
                .topK(10)   //查询前？条
                .build();

        List<Document> documents = vectorStore.similaritySearch(searchRequest);
        // 我眼睛疼 0.4498

        assert documents != null;
        System.out.println("搜索到文档数量:" +documents.size());
        for(Document document : documents) {
            System.out.println(document.getText());
        }
        return Result.success();
    }

}
